//index.js 
//获取应用实例
import regeneratorRuntime from '../../utils/runtime.js';
import { get } from '../../utils/Helpers';
const app = getApp()

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    news:{},
    poster_url: '',    //海报图片
    userInfo: {},  //用户信息
    vw: '',          //可使用窗口宽度
    vh: '',          //可使用窗口高度
    pixelRatio: '',  //设备像素比
    ctxWidth: '',    //画布宽度
    ctxHeight: '',   //画布高度
    posters: '',     //海报本地地址
    postersHeight: '',    //海报高度
    qrCode: '',   //二维码
    userImg:''
  },

  onLoad: function (options) {

    let that = this
    var id = options.productid;
    console.log(id)
    wx.request({
      url: app.siteInfo.siteroot + 'product_one',
      method: "post",
      data: {
        uid: app.siteInfo.uid,
        pid: app.siteInfo.pid,
        aid: id
      },
      success: function (res) {
        wx.hideLoading()
        wx.setNavigationBarTitle({
          title: res.data.one.title,
        })
        that.setData({
          news: res.data.one,
          userInfo: res.data.card
        }, () => { 
          that.getCanvasData();
        })
      }
    })
    return;
  },

  getCanvasData: async function () {
    let that = this
    let { vw, vh, pixelRatio, ctxWidth, ctxHeight, posters, postersHeight, userInfo, news, userImg, qrCode } = that.data
    // var poster_url = that.data.news.logo1 ? that.data.news.logo1 : that.data.news.logo;
    var poster_url = get(['logo1'], news) ? get(['logo1'], news) : get(['logo'], news);
    var QrCode = get(['qrcode'], news) ? get(['qrcode'], news) : get(['qrcode'], userInfo);
    console.log('poster_url:', poster_url)
    console.log('QrCode:', QrCode)
    wx.showLoading({
      title: '正在努力生成中...',
    })
    //获取设备信息
    wx.getSystemInfo({
      success: async function (res) {
        await new Promise((resolve, reject) => {
          that.setData({
            vw: res.windowWidth,         //可使用窗口宽度
            vh: res.screenHeight,        //可使用屏幕高度
            pixelRatio: res.pixelRatio,  //设备像素比
            ctxWidth: res.windowWidth * 9 / 10,    //画布宽度=屏幕宽度*90%
          }, () => {
            resolve(true)
          })
        })
        // 获取海报宽高
        await new Promise((resolve) => {
          wx.getImageInfo({
            src: poster_url ? poster_url : '',
            success: function (res) {
              console.log(1)
              let postersHeightnew = res.height * that.data.ctxWidth / res.width;
              that.setData({
                posters: res.path,
                postersHeight: postersHeightnew,
                ctxHeight: postersHeightnew + 240,
              }, () => {
                resolve(true)
              })
            },
            fail: function (e) {
              wx.hideLoading();
              wx.showToast({
                title: e.errMsg+'1',
                icon: 'none',
                duration: 2000
              })
            }
          })
        })
        // 获取用户头像
        await new Promise((resolve) => {
          wx.getImageInfo({
            src: app.siteInfo.customer.logo,
            success: function (res) {
              console.log(2)
              that.setData({
                userImg: res.path,
              }, () => {
                console.log('userImg')
                resolve(true)
              })
            },
            fail: function (e) {
              wx.hideLoading();
              wx.showToast({
                title: e.errMsg+'2',
                icon: 'none',
                duration: 2000
              })
            }
          })
        })

        // 获取小程序码
        await new Promise((resolve) => {
          wx.getImageInfo({
            src: QrCode ? QrCode : '',
            success: function (res) {
              console.log(3)
              that.setData({
                qrCode: res.path,
              }, () => {
                resolve(true)
              })
            },
            fail: function (e) {
              wx.hideLoading();
              wx.showToast({
                title: e.errMsg+'3',
                icon: 'none',
                duration: 2000
              })
            }
          })
        })

        wx.hideLoading()
        const ctx = wx.createCanvasContext('main')
        const vw = that.data.vw;
        const vh = that.data.vh;
        const ctxWidth = that.data.ctxWidth;
        const ctxHeight = that.data.ctxHeight;
        const postersHeight = that.data.postersHeight
        const posters = that.data.posters;
        const userImg = that.data.userImg;
        const qrCode = that.data.qrCode;
        const name = that.data.news.title + "        " + that.data.news.remark
        // 画背景色
        ctx.save()
        ctx.beginPath()
        ctx.setFillStyle('#fff') 
        ctx.fillRect(0, 0, ctxWidth, ctxHeight)
        ctx.restore()

        // 画头像
        ctx.save()
        ctx.beginPath()
        ctx.drawImage(userImg, 12, 15, 43, 43)
        ctx.restore()

        // 名字
        ctx.beginPath()
        ctx.setFillStyle('#000')
        ctx.setFontSize(14)
        ctx.setTextAlign('left')
        ctx.fillText(app.siteInfo.customer.wechat_name + "   给您推荐", 75, 40)
        ctx.restore()

        // posters
        ctx.beginPath()
        ctx.drawImage(posters, 12, 73, ctxWidth - 24, postersHeight);
        ctx.restore()

        // text
        ctx.beginPath()
        ctx.setFillStyle('#333')
        ctx.setFontSize(14)
        
        ctx.fillText(name, 12, ctxHeight - 140)
        ctx.restore()

        ctx.setFillStyle('#BBB')
        ctx.fillText(that.data.news.viewnum+'人关注', 12, ctxHeight - 95)
        ctx.restore()

        // 定金
        ctx.beginPath()
        ctx.setFillStyle('#E0323E')
        ctx.setFontSize(22)
        ctx.fillText("￥"+that.data.news.price, 12, ctxHeight - 60)
        ctx.restore()

        // 二维码
        ctx.beginPath();
        ctx.drawImage(qrCode, ctxWidth - 98, ctxHeight - 112, 70, 70);
        // ctx.drawImage(code, ctxWidth - 100, ctxHeight - 95, 70, 70);

        // 文字介绍
        ctx.beginPath()
        ctx.setFillStyle('#BBB')
        ctx.setFontSize(13) 
        ctx.setTextAlign('right')
        ctx.fillText("长按识别小程序码", ctxWidth - 12, ctxHeight - 22)
        ctx.draw(false, function (e) {
          wx.canvasToTempFilePath({

          })
        })
      }
    })
  },

  // 保存图片
  downloadImg: function () {
    var that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0.,
      width: that.data.ctxWidth,
      height: that.data.ctxHeight,
      destWidth: that.data.ctxWidth * that.data.pixelRatio,
      destHeight: that.data.ctxHeight * that.data.pixelRatio,
      canvasId: 'main',
      success: function (res) {
        console.log(res.tempFilePath)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({ 
              title: '保存成功',
              icon: 'success',
            })
          }
        })
      }
    })
  },

  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }, 
  onShareAppMessage: function () {
    wx.request({
      url: app.siteInfo.siteroot + 'relay',
      method: "post",
      data: {
        uid: app.siteInfo.uid,
        pid: app.siteInfo.pid,
        replaysource: "index"
      },
      success: function (res) { }
    })
    return {
      title: app.siteInfo.sharetitle,
      path: "/pages/index/index?share_card_id=" + app.siteInfo.pid + "&shareid=" + app.siteInfo.uid,
      success: function (a) {
        wx.request({
          url: app.siteInfo.siteroot + 'relay',
          method: "post",
          data: {
            uid: app.siteInfo.uid,
            pid: app.siteInfo.pid
          },
          success: function (res) { }
        })
      },
      fail: function (a) { }
    };
  }

})
